# coding=utf-8

from application import app
import hashlib, requests,random,string,json, urllib

"""
百度地图API接入
"""
class MapLibs():
    def __init__(self):
        self.ak = app.config["BAIDU_MAP"]["AK"]
        self.sk = app.config["BAIDU_MAP"]["SK"]

    def geocoder(self, latitude, longitude):
        """
        坐标反编码  经纬度换具体信息
        :param latitude:
        :param longitude:
        :return:
        """
        x, y = self.geoconv(latitude, longitude)
        queryStr = """/geocoder/v2/?location=%s,%s&output=json&latest_admin=1&ak=%s""" % (x, y, self.ak)
        url = self.url_coder(queryStr)
        r = requests.get(url)
        res = json.loads(r.text)
        return res


    def geoconv(self, latitude, longitude):
        """
        单坐标转换 WGS84  to  bd09ll
        :return:
        """
        queryStr = """/geoconv/v1/?coords=%s,%s&output=json&from=1&to=5&ak=%s""" % ( latitude, longitude, self.ak)
        url = self.url_coder(queryStr)
        r = requests.get(url)
        res = json.loads(r.text)
        crood = res["result"][0]
        x = crood["x"]
        y = crood["y"]
        return x, y


    def url_coder(self, queryStr):
        #
        """
        把url转码成为可以解析的格式
        :param queryStr:
        :return:
        """
        domain = """http://api.map.baidu.com"""
        sn = self.get_sn(queryStr)
        url = urllib.parse.quote(domain + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
        return url

    def get_sn(self, queryStr):
        """
        计算SN
        :param queryStr:
        :return:
        """
        encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
        rawStr = encodedStr + self.sk
        sn = hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest()
        return sn
